package com.gaohe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gaohe.common.R;
import com.gaohe.pojo.AddressBook;
import com.gaohe.pojo.User;
import com.gaohe.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    HttpServletRequest request;
    @Autowired
    private AddressBookService addressBookService;

    //地址展示
    @GetMapping("/list")
    public R<List<AddressBook>> list() {
        User user = (User) request.getSession().getAttribute("user");
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId, user.getId());
        List<AddressBook> addressBooks = addressBookService.list(lqw);
        return R.success(addressBooks);
    }

    //添加地址信息
    @PostMapping
    public R<String> addAddress(@RequestBody AddressBook addressBook) {
        User user = (User) request.getSession().getAttribute("user");
        addressBook.setUserId(user.getId());
        addressBookService.save(addressBook);
        return R.success("新增地址成功");
    }

    //修改默认地址
    @PutMapping("/default")
    public R<String> updateDefault(@RequestBody AddressBook addressBook) {
        addressBookService.up_default(addressBook);
        return R.success("修改默认地址成功");
    }

    //修改地址的回显
    @GetMapping("/{id}")
    public R<AddressBook> updateAddress1(@PathVariable("id") Long id) {
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper();
        lqw.eq(AddressBook::getId, id);
        AddressBook one = addressBookService.getOne(lqw);
        return R.success(one);
    }

    //修改地址信息提交
    @PutMapping
    public R<String> updateAddress2(@RequestBody AddressBook addressBook) {
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper();
        lqw.eq(AddressBook::getId, addressBook.getId());
        addressBookService.update(addressBook, lqw);
        return R.success("修改成功");
    }

    //显示订单默认送达地址
    @GetMapping("/default")
    public R<AddressBook> defaultAddress() {
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getIsDefault, 1);
        AddressBook one = addressBookService.getOne(lqw);
        return R.success(one);

    }


}
